'''
  封装执行用例所需的函数
'''

import logging
import json

logger = logging.getLogger('log')
# 导入所需的models
from ..models import ptTestRequestTestCase, ptTestHeards, ptResponseContentReport, \
    ptResponseReportResult, ptTestPublicInterface
from ..utilService.webSqlExe import ModelData
from ..utilService import methods, httpOperate, cmpJsonDL


class exeTestCase(object):
    '''
    封装执行用例所需的函数
    '''

    def singleeExecution(self, caseList):
        '''
        单个计划执行用例
        '''
        try:
            for i in range(len(caseList)):
                case = ptTestRequestTestCase.objects.filter(case_id=caseList[i])
                if case == None:
                    continue
                data = ModelData().dataBaseHandle(self,case.values()[0])  #
                caseResult = methods.method().JOBcheckCaseAll(data)
                sqldata = {
                    "sqlTrueFlasetypeLast": data["sqlTrueFlasetypeLast"],
                    "id": data["sqlChoiceLast"],
                    "sql": data["SQLinputLast"],
                    "SQLMomentum": data["SQLMomentumLast"],
                    "sqlClusionValueLast": data["sqlClusionValueLast"],
                }
                result =  methods.method().AssertionResults(request_result=data["request_result"],
                                                    result=caseResult["data"],
                                                    resultlist=caseResult["reuslt"],
                                                    sqldata=sqldata)
                casedata = ptTestRequestTestCase.objects.get(case_id=caseList[i])
                casedata.request_response = result["AssertionLsit"]  # 获取返回内容并且保存
                casedata.request_code = result["Assertion"]  # 返回状态，并且保存
                casedata.request_result_Assertion_content = caseResult["data"]
                casedata.save()
            return None
        except EOFError as e:
            logger.error(e)

    def singleeExecutionMore(self, caseList, id):
        '''
        异步执行单个计划用例，带进度条
        '''
        try:
            print('异步执行测试用例，进度条')
            Success = 0  # 成功
            Fail = 0  # 失败
            Skip = 0  # 未执行
            for i in range(len(caseList)):
                case = ptTestRequestTestCase.objects.filter(case_id=caseList[i])
                if case == None:
                    continue
                data = ModelData().dataBaseHandle(case.values()[0])  #
                caseResult =  methods.method().JOBcheckCaseAll(data)
                sqldata = {
                    "sqlTrueFlasetypeLast": data["sqlTrueFlasetypeLast"],
                    "id": data["sqlChoiceLast"],
                    "sql": data["SQLinputLast"],
                    "SQLMomentum": data["SQLMomentumLast"],
                    "sqlClusionValueLast": data["sqlClusionValueLast"],
                }
                result =  methods.method().AssertionResults(request_result=data["request_result"],
                                                    result=caseResult["data"],
                                                    resultlist=caseResult["reuslt"],
                                                    sqldata=sqldata)
                print('断言完毕-------')
                casedata = ptTestRequestTestCase.objects.get(case_id=caseList[i])
                casedata.request_response = result["AssertionLsit"]  # 获取返回内容并且保存
                casedata.request_code = result["Assertion"]  # 返回状态，并且保存
                casedata.request_result_Assertion_content = caseResult["data"]
                casedata.save()
                print('断言结果保存完毕-------')
                print('显示进度-------')

                k = i + 1
                currentProgress = int((k / len(caseList)) * 1000) / 1000  # 当前执行进度
                if k == len(caseList):  # 满进度
                    currentProgress = 1
                exe_progress_percentage = str(currentProgress * 100) + '%'  # 百分比进度

                reportProgress = ptResponseContentReport.objects.get(plan_id=id)  # 获取具体计划 傻逼了 ！！！一开始用的filter，我说为啥没有对应属性呢，这里要用get
                print('更新完毕-------',exe_progress_percentage,type(exe_progress_percentage))
                reportProgress.execution_progress = exe_progress_percentage  # 计划执行进度
                reportProgress.remark = "运行过，并且已更新对应进度"
                reportProgress.save() #
                print('更新完毕-------',reportProgress)
            reportData = ptResponseContentReport.objects.get(plan_id=id)  # 保存到对应报告内容中
            print('获取报告内容-------')
            # 并且修改对应报告内容中状态
            reportData.successs_case = Success
            reportData.fail_case = Fail
            reportData.skip_case = Skip
            reportData.save()
            reportDataResult = ptResponseReportResult(plan_id=reportData.plan_id, plan_name=reportData.plan_name,
                                                      successs_case=reportData.successs_case,
                                                      fail_case=reportData.fail_case, skip_case=reportData.skip_case,
                                                      case_total=reportData.case_total,
                                                      timing_open_close=reportData.timing_open_close)
            print('插入报表内容------->',reportDataResult)
            reportDataResult.save()  # 保存到对应报告结果中
            return None
        except EOFError as e:
            logger.error(e)

    def runRepositoryPublicMethod(self, id):
        '''
        运行依赖的公共方法，并且保存到数据库中
        '''
        publicInterface = ptTestPublicInterface.objects.get(request_id=id)
        url = publicInterface.url
        method = publicInterface.method
        request_data_type = publicInterface.request_data_type
        request_header_param = publicInterface.request_header_param
        if request_header_param == "":
            request_header_param = {}
        else:
            request_header_param = eval(request_header_param)
        request_data_content = publicInterface.request_data_content
        request_value = eval(publicInterface.request_value)
        methodname = str(request_data_type) + str(method)

        self.url = url
        self.headers = request_header_param
        self.params = eval(request_data_content)
        self.data = eval(request_data_content)
        self.cookies = {}
        print('post data;',self)
        # 进行请求 获取响应结果
        if methodname == "DATAGET":
            Result = httpOperate.ConfigHttp.dataget(self)
        if methodname == "DATAPOST":
            Result = httpOperate.ConfigHttp.datapost(self)
        if methodname == "JSONGET":
            Result = httpOperate.ConfigHttp.jsonget(self)
        if methodname == "JSONPOST":
            Result = httpOperate.ConfigHttp.jsonpost(self)
        valuelist = {}
        for i in range(len(request_value)):
            keyName = request_value[i]["newKey"]
            realkey = request_value[i]["realkey"]
            num = int(request_value[i]["newValue"])
            if num == "":  #  没有下标的
                value = cmpJsonDL.jsondict().get_target_value(keyName, Result.json(), [])
                print('public 无下标',value)
            else:  # 动态参数有下标 todo 存在问题
                value = cmpJsonDL.jsondict().get_target_value(keyName, Result.json(), [])[num]
                print('public 有下标--value',value)
            valuelist[realkey] = str(value)
        headers1 = ptTestHeards.objects.get(tpi_id=id)
        headers1.headrsValues = valuelist
        headers1.save()
        logger.info("--更新完成当前头部信息---%s" % headers1.headrsName)
        return valuelist
